import time
from asyncio import iscoroutinefunction
from functools import wraps

from mg_app_framework import get_logger, log_exception
from common.tool import fullname


def capture_log_exception(func):
    """
    异常日志打印函数
    :param func:
    :return:
    """

    @wraps(func)
    async def running_async_fun(*args, **kwargs):
        try:
            return await func(*args, **kwargs)
        except Exception as e:
            log_exception(e, fullname(func))

    @wraps(func)
    def running_fun(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            log_exception(e, fullname(func))

    return running_async_fun if iscoroutinefunction(func) else running_fun


def time_costs(func):
    """
    打印函数耗时操作函数
    :param func:
    :return:
    """

    @wraps(func)
    async def running_async_fun(*args, **kwargs):
        start_time = time.time()
        result = await func(*args, **kwargs)
        end_time = time.time()
        get_logger().info(
            f"func: {fullname(func)}, args: {args}, kwargs: {kwargs}, cost_time: {end_time - start_time}"
        )
        return result

    @wraps(func)
    def running_fun(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        get_logger().info(
            f"func: {fullname(func)}, args: {args}, kwargs: {kwargs}, cost_time: {end_time - start_time}"
        )
        return result

    return running_async_fun if iscoroutinefunction(func) else running_fun
